package com.zzyang.aop.demo.rpc.consumer.netty;


import com.zzyang.aop.demo.rpc.MyReferenceInvocation;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Getter;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author zhuoziyang
 * @date 2021/5/19 22:38
 */
@Getter
public class ConsumerNettyClient {

    private NettyClientChannelHandler clientChannelHandler = new NettyClientChannelHandler();

    public final String url;

    public ConsumerNettyClient(String url) {
        this.url = url;
    }

    public void start() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(clientChannelHandler);
                    }
                });

        String[] split = url.split(":");
        ChannelFuture connect = bootstrap.connect(split[0], Integer.parseInt(split[1]));

//        try {
//            connect.channel().closeFuture().sync();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    public <T> T send(MyReferenceInvocation invocation , Class<T> clazz) throws Exception{
        ChannelPromise channelPromise = clientChannelHandler.sendMessage(invocation);
        channelPromise.await(10L, TimeUnit.SECONDS);
        return clientChannelHandler.getResponse(clazz);
    }

}
